﻿// LdrInstruction.cs
// Contains a class for a ldr instruction

using System;


namespace armsim
{
    /// <summary>
    /// Class for an Arm LDR Instruction
    /// </summary>
    public class LdrInstruction : LoadStoreInstruction
    {

        /// <summary>
        /// Initializes a new LdrInstruction
        /// </summary>
        /// <param name="instruction">Grabs the info from here</param>
        public LdrInstruction(uint instruction)
            : base(instruction)
        {

        }

        /// <summary>
        /// Executes the instruction
        /// </summary>
        /// <param name="cpu">Executes from the cpu and stores the results in the cpu</param>
        public override void Execute(VirtualCPU cpu)
        {

            var rn = cpu.Registers.ReadRegistersDuringExecute(VirtualMemory.MapRegNoToRegMem(this.Rn));
            var offset = this.Offset.ComputeOffset(cpu);
            //var memory = cpu.RAM.ReadWord(rn + offset);
            var memory = this.U == 1u ? cpu.RAM.ReadWord(rn + offset) : cpu.RAM.ReadWord(rn - offset);
            cpu.Registers.WriteWord(VirtualMemory.MapRegNoToRegMem(this.Rd), memory);

        }


        /// <summary>
        /// Converts the instruction to assembly code
        /// </summary>
        /// <param name="cpu">grabs info from here</param>
        /// <returns>the assembly code</returns>
        public override string ToAssembly(VirtualCPU cpu)
        {
            return String.Format("LDR {0}", base.ToAssembly(cpu));
        }

    }
}
